package com.jiyinit.web.core.business.service;

import java.util.*;

import javax.annotation.Resource;

import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.web.core.business.dao.TabCoreTaskDao;
import com.jiyinit.web.core.business.dao.TabCoreUserTaskDao;
import com.jiyinit.web.core.business.dao.TabSendMessageDao;
import com.jiyinit.web.core.business.dto.MessageRequest;
import com.jiyinit.web.core.business.entity.TabCoreTask;
import com.jiyinit.web.core.business.entity.TabCoreUserTask;
import com.jiyinit.web.core.business.entity.TabSendMessageEntity;
import com.jiyinit.web.core.business.enums.CommonEnum;
import com.jiyinit.web.core.business.enums.OperationTypeConstant;
import com.jiyinit.web.core.business.enums.SystemConstant;
import com.jiyinit.web.core.business.vo.TaskInfoVo;
import com.jiyinit.web.core.common.util.MessagePush;
import org.springframework.stereotype.Service;

import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.web.core.business.dao.TabCoreTaskMessageDao;
import com.jiyinit.web.core.business.dto.TaskMessageRequest;
import com.jiyinit.web.core.business.entity.TabCoreTaskMessage;
import com.jiyinit.web.core.business.vo.TaskMessageVo;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author wuyuefeng
 * @version 1.0
 * @date 2017/4/11 17:59
 * @since 1.0
 */
@Service("core.taskMessageServiceImpl")
public class TaskMessageServiceImpl {
	
	@Resource(name = "core.tabCoreTaskMessageDao")
    private TabCoreTaskMessageDao tabCoreTaskMessageDao;

    @Resource(name = "core.tabCoreTaskDao")
    private TabCoreTaskDao tabCoreTaskDao;

    @Resource(name = "send.tabSendMessageDao")
    private TabSendMessageDao tabSendMessageDao;

    @Resource(name = "send.message" )
    private ReadMessageServiceImpl readMessageService;

    @Resource(name = "core.tabCoreUserTaskDao")
    private TabCoreUserTaskDao tabCoreUserTaskDao;

    @Resource(name ="core.jpushClientServiceImpl")
    private JpushClientServiceImpl jpushClientService;

    public List<TabCoreTaskMessage> findNewMessageList(List<TaskInfoVo> list){
        return tabCoreTaskMessageDao.findNewMessageList(list);
    }

    public int addDailyLogMessage1(MessageRequest request){
        int num = 0;
        //查询DailyLog对象
        TabCoreTask dailyTask = tabCoreTaskDao.findTaskById(request.getId());
        if(request.getTaskMessageId() == null) {//增加
            //写message表
            TabCoreTaskMessage message = new TabCoreTaskMessage();
            message.setMessageContent(request.getContent());
            message.setCreateTime(new Date());
            message.setCreateUid(request.getUserId());
            message.setTaskId(request.getId());
            message.setParentId(request.getParentId());

            if (request.getUserId().intValue() != dailyTask.getCreateUid().intValue()) {
                message.setMessageCla("leftBubble");
            } else {
                message.setMessageCla("rightBubble");
            }
            num = tabCoreTaskMessageDao.addTaskMessage(message);
        }else{
            //request.getTaskMessageId() != null 更新
            TabCoreTaskMessage tabCoreTaskMessage = tabCoreTaskMessageDao.findByPK(request.getTaskMessageId());
            tabCoreTaskMessage.setMessageContent(request.getContent());
            num = tabCoreTaskMessageDao.update(tabCoreTaskMessage);
        }

        //更新task的最后最该时间
        TabCoreTask task = new TabCoreTask();
        task.setTaskId(dailyTask.getTaskId());
        task.setEditTime(new Date());
        tabCoreTaskDao.update(task);


        if( request.getIsPush().intValue() == 1) {
            //查询所有的联系人
            List<TabCoreUserTask> userList = tabCoreUserTaskDao.getUserByTaskId(request.getId());
           // Integer[] users = new Integer[userList.size()];
            List<Integer> users = new ArrayList<>();
            int i = 0;
            for (TabCoreUserTask user : userList) {
                //if (user.getAlloterId().intValue() != request.getUserId()) {
                   // users[i] = user.getAlloterId();
                   // i++;
               // }
                if (user.getAlloterId().intValue() != request.getUserId()) {
                    users.add(user.getAlloterId());
                }
            }

            //写消息未读表
//            readMessageService.add(request.getUserId(), users, request.getFunId(), request.getId());
            readMessageService.add1(request.getUserId(), users, request.getFunId(), request.getId());

            //极光推送
            /*HashMap<String, String> sendMessages = new HashMap<>();
            sendMessages.put("content", request.getContent());
            sendMessages.put("id", dailyTask.getTaskId().toString());

            String[] pusers = new String[users.size()];
            for (int j = 0; j < users.size(); j++) {
                pusers[j] = users.get(j).toString();
            }
            jpushClientService.send(request.getChannel(), sendMessages, pusers);*/

            Map<String,String> returnStr = new HashMap<>();
            returnStr.put("createUid", request.getUserId().toString());
            returnStr.put("taskCla", String.valueOf(SystemConstant.DAILY_LOG));
            returnStr.put("taskStatus","0");
            returnStr.put("content", "日志:"+dailyTask.getTitle()+",有内容变更");
            returnStr.put("strikeType", "2");
            returnStr.put("taskTitle", dailyTask.getTitle());
            returnStr.put("taskId", String.valueOf(dailyTask.getTaskId()));
            returnStr.put("type", OperationTypeConstant.DAILYLOG_ADD_MESSAGE);
            returnStr.put("dsc", request.getContent());

            String[] pusers = new String[users.size()];
            for (int j = 0; j < users.size(); j++) {
                pusers[j] = users.get(j).toString();
            }
            if(request.getChannel()!=null&&request.getChannel().equals("01")){
                MessagePush messagePush = new MessagePush(returnStr,pusers);
            }else{
                MessagePush messagePush = new MessagePush(returnStr,pusers,"andriod");
            }
        }

        return num;
    }

    public PagingResult<TaskMessageVo> findByPage(MessageRequest request){
       return  tabCoreTaskMessageDao.findByPage(request);
    }

    public TabCoreTaskMessage findTodayMessage(Integer taskId){
        return tabCoreTaskMessageDao.findTodayMessage(taskId);
    }

    public int addDailyLogMessage(MessageRequest request){
        //写message表
        TabCoreTaskMessage message = new TabCoreTaskMessage();
        message.setMessageContent(request.getContent());
        message.setCreateTime(new Date());
        message.setCreateUid(request.getUserId());
        message.setTaskId(request.getId());
        message.setParentId(request.getParentId());

       //查询DailyLog对象
        TabCoreTask dailyTask = tabCoreTaskDao.findTaskById(request.getId());

        if(request.getUserId()!=dailyTask.getCreateUid()){
            message.setMessageCla("leftBubble");
        }else{
            message.setMessageCla("rightBubble");
        }
        int num = tabCoreTaskMessageDao.addTaskMessage(message);

        //查询所有的联系人
        List<TabCoreUserTask> userList = tabCoreUserTaskDao.getUserByTaskId(request.getId());
        Integer[] users = new Integer[userList.size()];
        int  i= 0;
        for (TabCoreUserTask user : userList){
            if(user.getAlloterId().intValue() != request.getUserId()) {
                users[i] =user.getAlloterId();
                i++;
            }
        }
        if(dailyTask.getCreateUid().intValue() != request.getUserId())
            users[i] = dailyTask.getCreateUid();
        //写消息未读表
        readMessageService.add(request.getUserId(),users,request.getFunId(),request.getId());

        //极光推送
        HashMap<String,String> sendMessages = new HashMap<>();
        sendMessages.put("content",request.getContent());
        sendMessages.put("id",dailyTask.getTaskId().toString());

        String[] pusers = new String[users.length];
        for (int j = 0; j <users.length ; j++) {
            pusers[j] = users[j].toString();
        }

        jpushClientService.send(request.getChannel(),sendMessages,pusers);

        return num;
    }
	
	/**
	 * 
	     * 说明
	     * @author wuyuefeng
	     * @create 2017年5月12日 上午11:54:53
	     * @param 
	     * @return
	 */
	public List<TaskMessageVo> findAllByTaskId(Integer taskId){
		List<TaskMessageVo> taskMessageVos = new ArrayList<TaskMessageVo>();
		taskMessageVos = tabCoreTaskMessageDao.findTaskMessageByTaskId(taskId);
		return taskMessageVos;
	}
	
	public List<TaskMessageVo> findAllTaskMessageByTaskId(Integer taskId){
		List<TaskMessageVo> taskMessageVos = new ArrayList<TaskMessageVo>();
		taskMessageVos = tabCoreTaskMessageDao.findAllTaskMessageByTaskId(taskId);
		return taskMessageVos;
	}
	
	
	public List<TaskMessageVo> findTaskMesByTaskId(TaskMessageRequest taskMessageRequest){
		List<TaskMessageVo> taskMessageVos = new ArrayList<TaskMessageVo>();
		taskMessageVos = tabCoreTaskMessageDao.findTaskMesByTaskId(taskMessageRequest);
		return taskMessageVos;
	}
	
	
	public PagingResult<TaskMessageVo> messageForPage(TaskMessageRequest taskMessageRequest){
		return tabCoreTaskMessageDao.messageForPage(taskMessageRequest);
	}
	
	
	/**
	 * 
	     * 说明 web端
	     * @author wuyuefeng
	     * @create 2017年5月12日 上午11:55:30
	     * @param 
	     * @return
	 */
	public int addTaskMessage(TabCoreTaskMessage tabCoreTaskMessage,TabCoreTask task){
        tabCoreTaskDao.update(task);
		return tabCoreTaskMessageDao.addTaskMessage(tabCoreTaskMessage);
	}
    /**
     *
     * 说明 手机端
     * @author wuyuefeng
     * @create 2017年5月12日 上午11:55:30
     * @param
     * @return
     */
    public int maddTaskMessage(TabCoreTaskMessage tabCoreTaskMessage,TabCoreTask task,String[] alloterIds){
        tabCoreTaskDao.update(task);
        //增加消息
        List<TabSendMessageEntity> mesList = new ArrayList<TabSendMessageEntity>();
        for(int i = 0;i<= alloterIds.length-1;i++ ){
            TabSendMessageEntity message = new TabSendMessageEntity();
            message.setTaskId(task.getTaskId());
            //message.setFunId(6);
            Integer taskCla=tabCoreTaskDao.findTaskById(task.getTaskId()).getTaskCla();
            message.setFunId(taskCla);
            message.setReceiveUserId(new Integer(alloterIds[i]));
            message.setIsRead(CommonEnum.IsRead.NOREAD.getCode());
            message.setIsDelete(CommonEnum.IsDelete.COMMON.getCode());
            message.setCreateId(tabCoreTaskMessage.getCreateUid());
            message.setCreateTime(new Date());
            mesList.add(message);
        }
        if(!Check.isNullCollection(mesList)){
            tabSendMessageDao.batchInsert(mesList);
        }
        return tabCoreTaskMessageDao.addTaskMessage(tabCoreTaskMessage);
    }
	
	/**
	 * 
	     * 说明
	     * @author wuyuefeng
	     * @create 2017年5月23日 上午10:33:58
	     * @param 
	     * @return
	 */
	public List<TaskMessageVo> findTaskMessageByParentId(Integer parentId){
		List<TaskMessageVo> taskMessageVos = new ArrayList<TaskMessageVo>();
		taskMessageVos = tabCoreTaskMessageDao.findTaskMessageByParentId(parentId);
		return taskMessageVos;
	}
}
